import React, { useRef, useState } from 'react';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable, PageContainer } from '@ant-design/pro-components';
import { Button, Tag, Modal, Card, Descriptions, message, Select, Space, Badge, Statistic, Alert } from 'antd';
import { EyeOutlined, CheckOutlined, CloseOutlined, UserOutlined, DollarOutlined, BankOutlined, WarningOutlined } from '@ant-design/icons';
import { getWithdrawals, reviewWithdrawal, getWithdrawalDetail, batchProcessWithdrawals } from '@/services/game-platform/api';
import type { GamePlatform } from '@/services/game-platform/typings';

const { Option } = Select;

const WithdrawalAuditList: React.FC = () => {
  const actionRef = useRef<ActionType>(null);
  const [selectedRecord, setSelectedRecord] = useState<GamePlatform.WithdrawalRecord | null>(null);
  const [reviewModalVisible, setReviewModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [batchModalVisible, setBatchModalVisible] = useState(false);
  const [reviewAction, setReviewAction] = useState<'APPROVE' | 'REJECT'>('APPROVE');
  const [rejectReason, setRejectReason] = useState('');
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);

  // 状态颜色映射
  const statusColorMap = {
    'PROCESSING': 'processing',
    'SUCCESS': 'success',
    'FAIL': 'error',
    'CANCELLED': 'default',
  } as const;

  // 状态文本映射
  const statusTextMap = {
    'PROCESSING': '处理中',
    'SUCCESS': '成功',
    'FAIL': '失败',
    'CANCELLED': '已取消',
  } as const;

  const columns: ProColumns<GamePlatform.WithdrawalRecord>[] = [
    {
      title: '提现单号',
      dataIndex: 'transferId',
      width: 160,
      render: (_, record: GamePlatform.WithdrawalRecord) => (
        <span style={{ fontFamily: 'monospace', fontSize: '12px' }}>
          {record.transferId}
        </span>
      ),
    },
    {
      title: '用户信息',
      dataIndex: 'username',
      width: 120,
      render: (_, record) => (
        <div>
          <div><UserOutlined /> {record.username}</div>
          <div style={{ fontSize: '12px', color: '#999' }}>
            {record.userNickname || '未设置昵称'}
          </div>
        </div>
      ),
    },
    {
      title: '提现金额',
      dataIndex: 'amount',
      width: 120,
      search: false,
      render: (_, record: GamePlatform.WithdrawalRecord) => (
        <Statistic
          value={record.amount}
          precision={2}
          prefix={<DollarOutlined />}
          valueStyle={{ fontSize: '14px', color: '#f50' }}
        />
      ),
    },
    {
      title: '收款信息',
      dataIndex: 'receiverAliAccount',
      width: 180,
      search: false,
      render: (_, record) => (
        <div>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <BankOutlined style={{ marginRight: 4 }} />
            <span>{record.receiverAliAccount}</span>
          </div>
          <div style={{ fontSize: '12px', color: '#999' }}>
            {record.receiverName}
          </div>
        </div>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (_, record: GamePlatform.WithdrawalRecord) => {
        const status = record.status as keyof typeof statusColorMap;
        return (
          <Badge
            status={statusColorMap[status] as any}
            text={statusTextMap[status] || status}
          />
        );
      },
      valueType: 'select',
      valueEnum: {
        PROCESSING: { text: '处理中', status: 'Processing' },
        SUCCESS: { text: '成功', status: 'Success' },
        FAIL: { text: '失败', status: 'Error' },
        CANCELLED: { text: '已取消', status: 'Default' },
      },
    },
    {
      title: '申请时间',
      dataIndex: 'createdAt',
      width: 160,
      valueType: 'dateTime',
      sorter: true,
    },
    {
      title: '处理时间',
      dataIndex: 'payDate',
      width: 160,
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '审核人',
      dataIndex: 'reviewedBy',
      width: 100,
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (_, record) => [
        <Button
          key="detail"
          type="link"
          size="small"
          icon={<EyeOutlined />}
          onClick={() => handleViewDetail(record)}
        >
          查看详情
        </Button>,
        record.status === 'PROCESSING' && (
          <Button
            key="approve"
            type="link"
            size="small"
            icon={<CheckOutlined />}
            style={{ color: '#52c41a' }}
            onClick={() => handleReview(record, 'APPROVE')}
          >
            通过
          </Button>
        ),
        record.status === 'PROCESSING' && (
          <Button
            key="reject"
            type="link"
            size="small"
            icon={<CloseOutlined />}
            style={{ color: '#ff4d4f' }}
            onClick={() => handleReview(record, 'REJECT')}
          >
            拒绝
          </Button>
        ),
      ].filter(Boolean),
    },
  ];

  // 查看详情
  const handleViewDetail = async (record: GamePlatform.WithdrawalRecord) => {
    try {
      setLoading(true);
      const response = await getWithdrawalDetail(record.transferId);
      if (response.code === 200 && response.data) {
        setSelectedRecord(response.data);
        setDetailModalVisible(true);
      } else {
        message.error(response.message || '获取详情失败');
      }
    } catch (error) {
      message.error('获取详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 审核操作
  const handleReview = (record: GamePlatform.WithdrawalRecord, action: 'APPROVE' | 'REJECT') => {
    setSelectedRecord(record);
    setReviewAction(action);
    setRejectReason('');
    setReviewModalVisible(true);
  };

  // 批量审核
  const handleBatchReview = (action: 'APPROVE' | 'REJECT') => {
    if (selectedRowKeys.length === 0) {
      message.error('请选择要审核的记录');
      return;
    }
    setReviewAction(action);
    setRejectReason('');
    setBatchModalVisible(true);
  };

  // 确认审核
  const handleConfirmReview = async () => {
    if (!selectedRecord) return;
    
    if (reviewAction === 'REJECT' && !rejectReason.trim()) {
      message.error('请填写拒绝原因');
      return;
    }

    try {
      setLoading(true);
      const response = await reviewWithdrawal(selectedRecord.transferId, {
        action: reviewAction,
        rejectReason: reviewAction === 'REJECT' ? rejectReason : undefined,
      });
      
      if (response.code === 200) {
        message.success(response.message || '审核成功');
        setReviewModalVisible(false);
        actionRef.current?.reload();
      }
    } catch (error) {
      message.error('审核失败');
    } finally {
      setLoading(false);
    }
  };

  // 确认批量审核
  const handleConfirmBatchReview = async () => {
    if (reviewAction === 'REJECT' && !rejectReason.trim()) {
      message.error('请填写拒绝原因');
      return;
    }

    try {
      setLoading(true);
      const response = await batchProcessWithdrawals({
        transferIds: selectedRowKeys,
        action: reviewAction,
        rejectReason: reviewAction === 'REJECT' ? rejectReason : undefined,
      });
      
      if (response.code === 200) {
        message.success(`批量审核成功，处理了 ${response.data.processedCount} 条记录`);
        setBatchModalVisible(false);
        setSelectedRowKeys([]);
        actionRef.current?.reload();
      }
    } catch (error) {
      message.error('批量审核失败');
    } finally {
      setLoading(false);
    }
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: React.Key[]) => {
      setSelectedRowKeys(keys as string[]);
    },
    getCheckboxProps: (record: GamePlatform.WithdrawalRecord) => ({
      disabled: record.status !== 'PROCESSING',
    }),
  };

  return (
    <PageContainer
      title="提现审核管理"
      subTitle="管理用户提现申请和审核"
    >
      <ProTable<GamePlatform.WithdrawalRecord>
        headerTitle="提现申请列表"
        actionRef={actionRef}
        rowKey="transferId"
        search={{
          labelWidth: 120,
        }}
        rowSelection={rowSelection}
        toolBarRender={() => [
          <Button
            key="batch-approve"
            type="primary"
            icon={<CheckOutlined />}
            disabled={selectedRowKeys.length === 0}
            onClick={() => handleBatchReview('APPROVE')}
          >
            批量通过
          </Button>,
          <Button
            key="batch-reject"
            danger
            icon={<CloseOutlined />}
            disabled={selectedRowKeys.length === 0}
            onClick={() => handleBatchReview('REJECT')}
          >
            批量拒绝
          </Button>,
          <Button
            key="refresh"
            onClick={() => actionRef.current?.reload()}
          >
            刷新
          </Button>,
        ]}
        request={async (params, sort) => {
          try {
            const response = await getWithdrawals({
              page: (params.current || 1) - 1,
              size: params.pageSize || 20,
              status: params.status as any,
              keyword: params.username,
              startDate: params.createdAt?.[0],
              endDate: params.createdAt?.[1],
            });
            
            if (response.code === 200) {
              // 后端返回的是数组，需要转换为前端期望的格式
              const rawData = Array.isArray(response.data) ? response.data : [];
              
              // 数据格式转换：将后端Transfer对象转换为前端期望的WithdrawalRecord格式
              const transformedData = rawData.map((item: any) => ({
                transferId: item.transferId,
                username: item.user?.username || '未知用户',
                userNickname: item.user?.nickname || '',
                amount: item.amount,
                status: item.status,
                receiverAliAccount: item.receiverAliAccount,
                receiverName: item.receiverName,
                description: item.description,
                createdAt: item.createdAt,
                updatedAt: item.updatedAt,
                payDate: item.payDate,
                reviewedBy: item.reviewerId ? '管理员' : null,
                reviewedAt: item.reviewedAt,
                rejectReason: item.rejectReason,
              }));
              
              return {
                data: transformedData,
                success: true,
                total: transformedData.length, // 当前暂时使用数组长度
              };
            }
            return {
              data: [],
              success: false,
              total: 0,
            };
          } catch (error) {
            console.error('获取提现记录失败:', error);
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        columns={columns}
        pagination={{
          defaultPageSize: 20,
          showSizeChanger: true,
        }}
      />

      {/* 详情模态框 */}
      <Modal
        title="提现申请详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>,
          selectedRecord?.status === 'PROCESSING' && (
            <Button
              key="approve"
              type="primary"
              icon={<CheckOutlined />}
              onClick={() => {
                setDetailModalVisible(false);
                handleReview(selectedRecord, 'APPROVE');
              }}
            >
              通过审核
            </Button>
          ),
          selectedRecord?.status === 'PROCESSING' && (
            <Button
              key="reject"
              danger
              icon={<CloseOutlined />}
              onClick={() => {
                setDetailModalVisible(false);
                handleReview(selectedRecord, 'REJECT');
              }}
            >
              拒绝审核
            </Button>
          ),
        ].filter(Boolean)}
        width={800}
      >
        {selectedRecord && (
          <div>
            <Descriptions title="提现信息" column={2} bordered>
              <Descriptions.Item label="提现单号" span={2}>
                <span style={{ fontFamily: 'monospace' }}>{selectedRecord.transferId}</span>
              </Descriptions.Item>
              <Descriptions.Item label="用户名">{selectedRecord.username}</Descriptions.Item>
              <Descriptions.Item label="用户昵称">{selectedRecord.userNickname || '未设置'}</Descriptions.Item>
              <Descriptions.Item label="提现金额">
                <Statistic
                  value={selectedRecord.amount}
                  precision={2}
                  prefix="¥"
                  valueStyle={{ color: '#f50' }}
                />
              </Descriptions.Item>
              <Descriptions.Item label="状态">
                <Badge
                  status={statusColorMap[selectedRecord.status as keyof typeof statusColorMap] as any}
                  text={statusTextMap[selectedRecord.status as keyof typeof statusTextMap]}
                />
              </Descriptions.Item>
            </Descriptions>

            <Descriptions title="收款信息" column={2} bordered style={{ marginTop: 16 }}>
              <Descriptions.Item label="收款账号">{selectedRecord.receiverAliAccount}</Descriptions.Item>
              <Descriptions.Item label="收款人姓名">{selectedRecord.receiverName}</Descriptions.Item>
              {selectedRecord.receiverBankAccount && (
                <Descriptions.Item label="银行账号">{selectedRecord.receiverBankAccount}</Descriptions.Item>
              )}
              <Descriptions.Item label="描述" span={2}>{selectedRecord.description}</Descriptions.Item>
            </Descriptions>

            <Descriptions title="时间信息" column={2} bordered style={{ marginTop: 16 }}>
              <Descriptions.Item label="申请时间">{selectedRecord.createdAt}</Descriptions.Item>
              <Descriptions.Item label="更新时间">{selectedRecord.updatedAt || '-'}</Descriptions.Item>
              <Descriptions.Item label="处理时间">{selectedRecord.payDate || '-'}</Descriptions.Item>
              <Descriptions.Item label="审核时间">{selectedRecord.reviewedAt || '-'}</Descriptions.Item>
            </Descriptions>
            
            {selectedRecord.reviewedBy && (
              <Descriptions title="审核信息" column={2} bordered style={{ marginTop: 16 }}>
                <Descriptions.Item label="审核人">{selectedRecord.reviewedBy}</Descriptions.Item>
                {selectedRecord.rejectReason && (
                  <Descriptions.Item label="拒绝原因" span={2}>{selectedRecord.rejectReason}</Descriptions.Item>
                )}
              </Descriptions>
            )}
          </div>
        )}
      </Modal>

      {/* 审核模态框 */}
      <Modal
        title={`${reviewAction === 'APPROVE' ? '通过' : '拒绝'}审核`}
        open={reviewModalVisible}
        onCancel={() => setReviewModalVisible(false)}
        onOk={handleConfirmReview}
        confirmLoading={loading}
      >
        {selectedRecord && (
          <div>
            <p>确定要{reviewAction === 'APPROVE' ? '通过' : '拒绝'}用户 <strong>{selectedRecord.username}</strong> 的提现申请吗？</p>
            <p>提现金额：<strong>¥{selectedRecord.amount.toFixed(2)}</strong></p>
            <p>收款账号：<strong>{selectedRecord.receiverAliAccount}</strong></p>
            {reviewAction === 'REJECT' && (
              <div style={{ marginTop: 16 }}>
                <label>拒绝原因：</label>
                <Select
                  style={{ width: '100%', marginTop: 8 }}
                  placeholder="请选择拒绝原因"
                  value={rejectReason}
                  onChange={setRejectReason}
                  allowClear
                >
                  <Option value="账户信息有误">账户信息有误</Option>
                  <Option value="收款人信息不匹配">收款人信息不匹配</Option>
                  <Option value="余额不足">余额不足</Option>
                  <Option value="涉嫌违规操作">涉嫌违规操作</Option>
                  <Option value="系统维护暂停提现">系统维护暂停提现</Option>
                  <Option value="其他原因">其他原因</Option>
                </Select>
              </div>
            )}
          </div>
        )}
      </Modal>

      {/* 批量审核模态框 */}
      <Modal
        title={`批量${reviewAction === 'APPROVE' ? '通过' : '拒绝'}审核`}
        open={batchModalVisible}
        onCancel={() => setBatchModalVisible(false)}
        onOk={handleConfirmBatchReview}
        confirmLoading={loading}
      >
        <div>
          <p>确定要{reviewAction === 'APPROVE' ? '通过' : '拒绝'} <strong>{selectedRowKeys.length}</strong> 条提现申请吗？</p>
          {reviewAction === 'REJECT' && (
            <div style={{ marginTop: 16 }}>
              <label>拒绝原因：</label>
              <Select
                style={{ width: '100%', marginTop: 8 }}
                placeholder="请选择拒绝原因"
                value={rejectReason}
                onChange={setRejectReason}
                allowClear
              >
                <Option value="账户信息有误">账户信息有误</Option>
                <Option value="收款人信息不匹配">收款人信息不匹配</Option>
                <Option value="系统维护暂停提现">系统维护暂停提现</Option>
                <Option value="批量审核拒绝">批量审核拒绝</Option>
                <Option value="其他原因">其他原因</Option>
              </Select>
            </div>
          )}
        </div>
      </Modal>
    </PageContainer>
  );
};

export default WithdrawalAuditList;
